package com.example.hospital.appointment.controller;

import com.example.hospital.appointment.pojo.UploadFile;
import com.example.hospital.appointment.repository.UploadFileRepository;
import com.example.hospital.appointment.service.UploadFileService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import static com.example.hospital.appointment.controller.NdoctorInfControler.ROOT;

/**
 */
@Controller
@RequestMapping("file")
public class FileController {

    private final static Logger logger = LoggerFactory.getLogger(FileController.class);

    private String savePath="C:\\Users\\qi\\Desktop\\上传\\";

    @Autowired
    private UploadFileService uploadFileService;

/*                  Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));*/
    @RequestMapping("health")
    public String healthcareservices(Model model){
        List<UploadFile> uploadFiles = uploadFileService.findAll();
        model.addAttribute("files",uploadFiles);
        return "healthcareservices";
    }

    @GetMapping("download/{id}")
    public ResponseEntity<byte[]> download(HttpServletResponse res, @PathVariable Integer id) throws UnsupportedEncodingException {
        try {
            UploadFile fileInfo = uploadFileService.getUploadFileByFileId(id);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    URLEncoder.encode(fileInfo.getName(), "UTF-8"));
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(fileInfo.getPath()+"."+fileInfo.getType())),
                    headers, HttpStatus.CREATED);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return null;
    }

    @PostMapping("uploadFile")
    @ResponseBody
    public String uploadFile(MultipartFile file) {
        //getOriginalFilename() 获取上传文件的原名
        System.out.println("file: " + file.getOriginalFilename());
        String fileName = file.getOriginalFilename(); //.substring(file.getOriginalFilename().lastIndexOf("."));

        UploadFile uploadfile = new UploadFile();

        uploadfile.setPath(savePath + fileName);
        uploadfile.setName(fileName.split("\\.")[0]);
        uploadfile.setType(fileName.split("\\.")[1]);
        uploadFileService.save(uploadfile);

        try {
            file.transferTo(new File(savePath + fileName));//将文件写到指定路径的指定文件内
        } catch (IOException e) {
            logger.error(e.getMessage());
            return "error";
        }
        return fileName;
    }

    @PostMapping("uploadFiles")
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request)
    {

        String fileNames = "";

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request))
        {
            // 转换成多部分request
                    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                    // 取得request中的所有文件名
                    Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext())
            {
                            // 取得上传文件
                            MultipartFile file = multiRequest.getFile(iter.next());
                            // 取得当前上传文件的文 件名称
                            String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                try {
                            file.transferTo(new File(savePath + fileName));
                            fileNames += fileName + "||";
                } catch (IOException e) {
                            logger.error(e.getMessage());
                            return "error";
                }
            }

        }
        return fileNames;
    }

    @ResponseBody
    @GetMapping("/getFile")
    public StringBuffer getFile(){
                    UploadFile uploadFile = uploadFileService.getUploadFileByFileId(14);
                    String path = uploadFile.getPath()+"."+uploadFile.getType();
                    FileInputStream fileInputStream = null;
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
                    fileInputStream = new FileInputStream(path);

                    byte[] buffer=new byte[1024];
                    int length=-1;
                    while((length = fileInputStream.read(buffer)) != -1){
                        bos.write(buffer,0,length);
            }
                    System.out.println(bos.toString());
                    bos.close();
                    fileInputStream.close();
        } catch (FileNotFoundException e) {
                    e.printStackTrace();
        }catch (IOException e){
        }

                    return new StringBuffer(bos.toString());
    }


}
